<?php
namespace App\Http\Controllers\Item;

use App\Http\Controllers\Controller;

class BaseController extends Controller
{
    //所有项目基础控制器

    /**
     * 接口返回
     */
    public function toJson($code = 0, $msg = '', $data = [], $total = 0)
    {
        if ($code == 0) $code = 200;
        if ($code == -2) $code = -102;
        if (!$msg) $msg = 'success';
        return [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
            'total' => $total,
        ];
    }

    /**
     * 构建CURL请求，单线程
     * @param $url 请求地址
     * @param $string 参数拼接的字符串
     * @param $method 请求方式：put、post、get、delete
     * @return $json
     */
    public function setCurl($url = '', $string = '', $method = 'get')
    {
        if (!$url) {
            return array('code'=>-2 ,'msg'=>'没有接口地址');
        }
        if (!$method) {
            return array('code'=>-2 ,'msg'=>'没有请求方式');
        }
        $curl = curl_init(); //初始化
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if ($method == 'post') {
            curl_setopt($curl, CURLOPT_FORBID_REUSE, 1);
            curl_setopt($curl, CURLOPT_FRESH_CONNECT, 1);
            curl_setopt($curl, CURLOPT_ENCODING, '');
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $string);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json', 'Content-Length: ' . strlen($string)
            ));
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);
        $output = curl_exec($curl);
        curl_close($curl);
        //ddd($output);
        if (!$output) {
            return array('code'=>-1, 'msg'=>'请求失败', 'data' => $output);
        }
        $items = json_decode($output,true);
        return array('code' => 0, 'msg' => 'success', 'data' => $items);
    }
}